<template>
  <div class="app-container" style="padding:0">

    <div class="topLine">
      <!-- 搜索 -->
      <el-form ref="queryForm" :model="listQuery" :inline="true" label-width="68px">
        <el-form-item label="模板名称">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入模板名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增 </el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除 </el-button>
      </div>

    </div>

    <el-table v-loading="loading" :data="list" empty-text="暂无数据" @selection-change="handleSelectionChange">i
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="模板名称" align="center" prop="name" />
      <el-table-column label="模板描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="视频流" align="center" prop="videoStream1" />
      <el-table-column label="创建时间" align="center" prop="create_time" :show-overflow-tooltip="true">
        <template slot-scope="scope">{{ scope.row.create_time }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getAllTemplates"
    />

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>

        <el-form-item label="人员:" prop="userIds" :rules="tagRules">
          <el-button type="primary" @click="chooseMember()">选择人员</el-button>
          <div v-if="selectedMember.length !== 0" class="members-selectedLine">
            <el-tag
              v-for="tag in selectedMember"
              :key="tag.phone"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag.username }}
            </el-tag>
          </div>

          <el-dialog
            title="选择人员"
            :visible.sync="memberBox"
            width="50%"
            class="memberBox"
            append-to-body
          >
            <div class="memberIn">
              <div class="memberIn-left">
                <el-tree
                  ref="tree"
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  default-expand-all
                  @node-click="handleNodeClick"
                />
              </div>
              <div class="memberIn-right">
                <div v-if="!currentDeptId" style="text-align: center;margin-top: 20%;">请在左边点击组织树进行选择</div>
                <table v-else class="styled-table">
                  <tr>
                    <th>选择</th>
                    <th>用户名</th>
                    <th>班级</th>
                    <th>手机</th>
                    <th>状态</th>
                  </tr>
                  <tr v-for="item in getTables[currentDeptId]" :key="item.id">
                    <td>
                      <input type="checkbox" :checked="isSelected(item.id)" @change="toggleSelection(item)" />
                    </td>
                    <td>{{ item.username }}</td>
                    <td>{{ item.department.name }}</td>
                    <td>{{ item.phone }}</td>
                    <td>{{ item.status }}</td>
                  </tr>
                </table>
                <!-- 分页 -->
                <pagination
                  v-show="totalMember > 0"
                  :total="totalMember"
                  :page.sync="queryParams.page"
                  :limit.sync="queryParams.limit"
                  @pagination="getList(currentDeptId)"
                />
              </div>
            </div>

            <div class="selectedLine">
              已选：
              <el-tag
                v-for="tag in selectedMember"
                :key="tag.phone"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag.username }}
              </el-tag>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="memberBox = false">取 消</el-button>
              <el-button type="primary" @click="memberBox = false">确 定</el-button>
            </span>
          </el-dialog>
        </el-form-item>

        <el-form-item label="会议视频流">
          <el-input v-model="form.videoStream1" placeholder="学生摄像机画面地址" />
        </el-form-item>

        <el-form-item label="模板描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
// 接口
import { listUser } from '@/api/system/user'
import { getTemplatesByPage, getTemplateDetail, updateTemplateDetail, addTemplate, deleteTemplate } from '@/api/main'
import { listDept } from '@/api/system/dept'

export default {
  name: 'TemplateMeeting',
  components: { },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      totalMember: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        type: 2
      },
      form: { },
      // 表单校验
      rules: {
        userIds: [
          { required: true, message: '人员不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      },
      tagRules: [
        {
          validator: (rule, value, callback) => {
            if (this.selectedMember.length === 0) {
              callback(new Error('人员不能为空'))
            } else {
              callback()
            }
          },
          trigger: 'blur',
          required: true
        }
      ],
      // 组织树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      getTables: {}, // 存储所有表格数据 { deptId: { list: [] } }
      currentDeptId: null, // 当前选中的部门ID
      // 已选的人员
      selectedMember: [
        // { id: 13, username: '张翠花', deptId: 11 },
        // { id: 15, username: '李莉', deptId: 11 },
        // { id: 27, username: '黄大壮', deptId: 11 },
        // { id: 41, username: '1212', deptId: 2 }
      ],
      memberBox: false, // 选择人员弹窗
      // 用户表格数据
      userList: [],
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        username: undefined,
        nickname: undefined,
        status: undefined,
        deptId: undefined
      },
      // 查询参数
      queryParams2: {
        page: 1,
        limit: 10,
        username: undefined,
        nickname: undefined,
        status: undefined,
        deptId: undefined
      }
    }
  },
  computed: {
    selectedIds() {
      return this.selectedMember.map(item => item.id)
    }
  },
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    // 获取模板-分页
    this.getAllTemplates()
    // /////////
    this.getTreeselect()
  },
  methods: {
    /** 查询组织下拉树结构 */
    getTreeselect() {
      listDept().then(response => {
        this.deptOptions = response.data
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    // 获取模板
    getAllTemplates() {
      this.loading = true
      getTemplatesByPage(this.listQuery).then(response => {
        this.list = response.data.template_data
        this.list.forEach(item => {
          if (item.create_time) {
            item.create_time = item.create_time.replace('T', ' ')
          }
        })
        this.total = response.data.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      this.selectedMember = []
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        userIds: undefined,
        code: undefined,
        description: undefined,
        department_id: undefined,
        sampling_interval: undefined,
        videoStream1: undefined,
        videoStream2: undefined
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.listQuery.page = 1
      this.getAllTemplates()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        type: 2
      }
      this.handleQuery()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增模板'
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTemplateDetail(id).then(response => {
        this.open = true
        this.title = '修改模板信息'
        this.form = response.data.template_data
        this.selectedMember = response.data.template_users
      })
    },

    chooseMember() { // 点击选择人员时，将所有已选人员按照id不同进行分类
      this.memberBox = true
    },

    handleClose(tag) {
      this.selectedMember.splice(this.selectedMember.indexOf(tag), 1)
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.queryParams2.deptId = data.id
      this.getListForTree(data.id)
    },
    getListForTree(deptId) {
      listUser(this.queryParams2).then(response => {
        this.$set(this.getTables, deptId, response.data.items)
        this.currentDeptId = deptId
        this.totalMember = response.data.total
      })
    },
    /** 查询用户列表 */
    getList(deptId) {
      listUser(this.queryParams).then(response => {
        this.$set(this.getTables, deptId, response.data.items)
        this.currentDeptId = deptId
        this.totalMember = response.data.total
      })
    },
    // 判断某个 id 是否已选中
    isSelected(id) {
      return this.selectedMember.some(member => member.id === id)
    },

    // 选中/取消选中
    toggleSelection(item) {
      const index = this.selectedMember.findIndex(member => member.id === item.id)
      if (index === -1) {
        this.selectedMember.push(item)
      } else {
        this.selectedMember.splice(index, 1)
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteTemplate(ids)
      }).then(() => {
        this.getAllTemplates()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },

    /** 提交按钮 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id === undefined) {
            // 新增
            this.form.type = 2
            this.form.userIds = this.selectedIds
            addTemplate(this.form).then(response => {
              if (response.code === 20000) {
                this.msgSuccess(response.message)
                this.open = false
                this.getAllTemplates()
                this.selectedMember = []
              }
            })
          } else {
            // 修改
            this.form.type = 2
            this.form.userIds = this.selectedIds
            updateTemplateDetail(this.form).then(response => {
              if (response.code === 20000) {
                this.msgSuccess(response.message)
                this.open = false
                this.getAllTemplates()
                this.selectedMember = []
              } else {
                this.msgSuccess(response.message)
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

  }
}
</script>

<style>
.topLine{
  padding:20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
}
.el-table .el-table__header-wrapper th{
  background: #e1ecfa;
}
.topLine .el-form-item{
  margin-bottom: 0;
}
.selectedLine{
  border-top: 1px solid #ddd;
  padding-top:10px;
}
.selectedLine span{
  margin: 0 10px 10px 0;
}
.members-selectedLine{
  background: #fff;
  border:1px solid #dcdfe6;
  margin-top:6px;
  padding:6px 8px;
  border-radius: 5px;
}
.members-selectedLine span{
  margin-right: 8px;
}
.memberBox .el-dialog__body{
  padding:0px 20px 20px
}
.memberIn{
  display: flex;
  height: 476px;
  border-top: 1px solid #ddd;
}
.memberIn-left{
  width:260px;
  border-right: 1px solid #ddd;
}
.memberIn-right{
  flex:1;
}
.memberIn-right .el-table--medium th, .el-table--medium td {
    padding: 7px 0;
}
</style>
